package com.spzx.product.service.impl;




import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.core.web.page.PageDomain;
import com.spzx.common.core.web.page.TableSupport;
import com.spzx.product.domain.ProductUnit;
import com.spzx.product.mapper.ProductUnitMapper;
import com.spzx.product.service.ProductUnitService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Wrapper;


//需要继承ServiceImpl
@Service
public class ProductUnitServiceImpl extends ServiceImpl<ProductUnitMapper, ProductUnit>
            implements ProductUnitService{



    @Override
    public Page selectProductUnitList(ProductUnit productUnit) {
        //1.通过工具获得PageDomain TableSupport
        PageDomain pageDomain = TableSupport.getPageDomain();
        //2.封装 mp需要的page分页数据
        Page<ProductUnit> page = new Page<>(pageDomain.getPageNum(),pageDomain.getPageSize());
        //利用Wrappers封装的方法lambdaQuery来使用动态sql
        LambdaQueryWrapper<ProductUnit> productUnitLambdaQueryWrapper = Wrappers.lambdaQuery(ProductUnit.class);

        //如果productUnit.name不为NULL设置 动态sql条件
        productUnitLambdaQueryWrapper.like(productUnit.getName() != null
                , ProductUnit::getName
                , productUnit.getName());


        Page<ProductUnit> productUnitPage = baseMapper.selectPage(page, productUnitLambdaQueryWrapper);

        return productUnitPage;
    }

    @Override
    public int saveProductUnit(ProductUnit productUnit) {

        //检查商品单位是否存在调用方法
        checkProductUnitName(productUnit);

        return baseMapper.insert(productUnit);
    }




    //检查商品单位是否存在
    @Override
    public void checkProductUnitName(ProductUnit productUnit){
        Long id = productUnit.getId()==null?-1:productUnit.getId();

        ProductUnit one = baseMapper.selectOne(new LambdaQueryWrapper<ProductUnit>()
                .eq(ProductUnit::getName, productUnit.getName()));
        if (one !=null && !id.equals(one.getId())){
            throw new ServiceException("商品单位已存在");
        }

    }




}
